<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="merchantName" label="商品名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="商品名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="businessQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="proList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="商品名称"
          prop="productName"
          width="150"
          align="center"
        />
        <el-table-column
          label="商品价格"
          prop="price"
          width="150"
          align="center"
        />
        <el-table-column
          label="库存数量"
          prop="stockQuantity"
          width="150"
          align="center"
        />
        <el-table-column
          label="商家名称"
          prop="merchantName"
          width="150"
          align="center"
        />
        <el-table-column label="商品描述" prop="description" min-width="100" />
        <el-table-column
          label="商品类别"
          prop="category"
          width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="businessFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="formData.productName"
            placeholder="请输入商品名称"
          />
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input v-model="formData.price" placeholder="请输入商品价格" />
        </el-form-item>

        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input
            v-model="formData.stockQuantity"
            placeholder="请输入库存数量"
          />
        </el-form-item>

        <el-form-item label="商家名称" prop="merchantName">
          <el-input
            v-model="formData.merchantName"
            placeholder="请输入商家名称"
          />
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="formData.description"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-input v-model="formData.category" placeholder="请输入商品分类" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  addPro,
  deletePro,
  getProForm,
  getProPage,
  updatePro,
} from "@/api/pro/index";
import { ProQuery, ProForm, ProPageVO } from "@/api/pro/type";

defineOptions({
  name: "Pro",
  inheritAttrs: false,
});

const dateTimeRange = ref(undefined);
const queryFormRef = ref(ElForm);
const businessFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ProQuery>({
  pageNum: 1,
  pageSize: 10,
});

const proList = ref<ProPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<ProForm>({
  id: undefined,
});

const rules = reactive({
  merchantName: [
    { required: true, message: "请输入商家名称", trigger: "blur" },
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
  ],
  contactEmail: [
    { required: true, message: "请输入联系人邮箱", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
  ],
  address: [{ required: true, message: "请输入商家地址", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getProPage(queryParams)
    .then(({ data }) => {
      proList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function businessQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  dateTimeRange.value = undefined;
  handleQuery();
}

/** 行checkbox 选中事件 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 打开商家表单弹窗 */
function openDialog(roleId?: number) {
  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改商品信息";
    getProForm(roleId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增商品信息";
  }
}

/** 角色保存提交 */
function handleSubmit() {
  businessFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = formData.id;
      if (Id) {
        updatePro(Id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            businessQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addPro(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            businessQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  businessFormRef.value.resetFields();
  businessFormRef.value.clearValidate();

  formData.id = undefined;
}

/** 删除角色 */
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deletePro(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        businessQuery();
      })
      .finally(() => (loading.value = false));
  });
}
onMounted(() => {
  handleQuery();
});
</script>
